// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};
/*
12-28-10 Added entrymethod option "timestamp"
	Fixed linkTableName creation, plus vaidation for proper linked table formation
7-24-09 Added entrymethod option "hidden" to dropdown (ESS)
7-23-09 optionsArray was not resetting, therefore not allowing multiple dropDown menus on the spec sheet > FIXED (ESS)
*/


	//#############################################################################
	//################## 		 BEGIN SET BEHAVIORS 		  #####################
	//#############################################################################
	
	var fieldClone, tableClone;
	
	/* #####################################
	* function setTableBehaviors()
	*		- cloneTable button
	*		- deleteTable button
	*		- tableCollapse button
	*
	########################################*/	
	jQuery.setTableBehaviors = function () {
		//alert("setTableBehaviors()");
				
		// ### UNBIND ALL BEHAVIORS FROM BUTTONS ###
		$(".cloneTable").unbind();
		$(".deleteTable").unbind();
		$(".tableCollapse").unbind();
		
		// ### REDEFINE ALL BEHAVIORS FOR BUTTONS ###
		$(".cloneTable").click(function () {
			tableClone = $(this).parent().clone();
			$(this).parent().after(tableClone);
			$.setFieldBehaviors();	
			$.setTableBehaviors();
		}); //end .cloneTable function
		
		$(".deleteTable").click(function () {
			$(this).parent().remove();
		}); //end .deleteTable function
		
		$(".tableCollapse").toggle(
			function () {
				parentTable = $(this).parent();
				//alert($(this).attr("class"));
				$(this).html("&nbsp;+&nbsp;");
				parentTable.find(".deleteTable, .newField, .cloneTable, .collapseAllFields, .field").hide();
			},
			function () {
				parentTable = $(this).parent();
				$(this).html("&#151;");
				parentTable.find(".deleteTable, .newField, .cloneTable, .collapseAllFields, .field").show();
			}
		); //end .tableCollapse function
		$.setFieldBehaviors();
	}; //end setTableBehaviors()
	
	/* #####################################
	* function setTableBehaviors()
	*		- newField button
	*		- cloneField button
	*		- deleteField button
	*		- fieldCollapse button
	*		- addOption button
	*		- deleteOption button
	*		- .entryMethod dropDown handler
	*		- .collapseAllFields button
	########################################*/	
	jQuery.setFieldBehaviors = function () {
		//alert("setFieldBehaviors()");
		
		var optContainerStr = "<div class='optionsContainer' id='options'>"+
			"<div class='addOption addButton' id'='addOption'>+ Option</div><input class='inputField' type=\"hidden\" name=\"optionsEnd\"></div>";
				
		var optionHTML = "<div class='dropDownOption' id='option 1_1_1'>Option : <input class='inputField' type='text' name='option'><div class='deleteOption'>Delete</div></div>";
				
		var relatedChildHTML = "<div class='relatedChild'>Child Table Name : <input class='inputField' type='text' name='child_tablename'><br/>Child Field Name : <input class='inputField' type='text' name='child_fieldname'></div>";

		// ### UNBIND ALL BEHAVIORS FROM BUTTONS ###
		$(".newField").unbind();
		$(".cloneField").unbind();
		$(".deleteField").unbind();
		$(".fieldCollapse").unbind();
		$(".addOption").unbind();
		$(".deleteOption").unbind();
		$(".entrymethod select").unbind();
		$(".collapseAllFields").unbind();		
		
		// ### REDEFINE ALL BEHAVIORS FOR BUTTONS ###
		
		$(".newField").click(function() {
			$(this).before($('#templates .field').clone());
/* 			console.log($('#templates .field').clone()); */
			$.setFieldBehaviors();
		}); //end function newField.click()
		
		$(".cloneField").click(function () {
			var origField = $(this).closest('.field'),
					fieldClone = origField.clone(),

			oldSQLdatatype = origField.find(".sqldatatype select").val();
			fieldClone.find(".sqldatatype select").val(oldSQLdatatype);

			oldEntryMethod = origField.find(".entrymethod select").val();
			fieldClone.find(".entrymethod select").val(oldEntryMethod);
			
			oldFrontList = origField.find(".frontlist select").val();
			fieldClone.find(".frontlist select").val(oldFrontList);
			
			oldBackList = origField.find(".backlist select").val();
			fieldClone.find(".backlist select").val(oldBackList);

			$(this).closest('.field').after(fieldClone);

			$.setFieldBehaviors();
		}); //end .cloneField function
		
		$(".deleteField").click(function() {
			numOfFields = $(this).parent().parent().find(".field").length;
			//alert(numOfFields + " fields");
			if (numOfFields <= 1){
				//alert("last field...deleting table");
				$(this).parent().parent().remove();
			} else
				$(this).parent().remove();
		}); //end .deleteField function
		
		$(".fieldCollapse").toggle(
			function () {
				//alert($(this).attr("class"));
				$(this).html("&nbsp;+&nbsp;");
				$(this).parent().find(".deleteField, .cloneField, .fieldContents").hide();
			},
			function () {
				//alert($(this).attr("class"));
				$(this).html("&#151;");
				$(this).parent().find(".deleteField, .cloneField, .fieldContents").show();
			}
		); //end .fieldCollapse function

		$(".addOption").click(function() {
			$(this).before(optionHTML);
			$.setFieldBehaviors();
		}); //end .addOption function
		
		$(".deleteOption").click(function() {
			numOfOpts = $(this).parent().parent().children().length - 2;
			//alert(numOfOpts + " options");
			if (numOfOpts <= 1) {
				$(this).parent().parent().parent().find(".entrymethod select").val('textField');
				$(this).parent().parent().remove();
			} else
				$(this).parent().remove();		
		}); //end .deleteOption function
		
		$(".entrymethod select").bind("change", function(){
			selectedValue = $(this).attr('value');
			previousSelection = $(this).parent().next().attr('class');
			if ((previousSelection == "optionsContainer") || (previousSelection == "thumbChild") || (previousSelection == "relatedChild") || (previousSelection == "linkedChildTable")) {
				$(this).parent().next().remove();
			}

			switch (selectedValue) {
				case "dropDown":
					var optsExist = $(this).parent().next().hasClass("optionsContainer");
					//if an options list doesn't exist already -> make one
					if (!optsExist) {
						//alert("creating opts list");
						$(this).parent().after(optContainerStr);
						$(this).parent().next().find('.addOption').before(optionHTML);
						$.setFieldBehaviors();	
					}	
					break;
				case "fileUploadCrop":
					thumbFieldHTML = $('#templates .thumbChild');
					$(this).parent().after(thumbFieldHTML);
					break;
				case "dropDown_related":
					$(this).parent().after(relatedChildHTML);
					break;
				case "date":
				case "time":
				case "timeStamp":
				case "dateTime":
					datatype = selectedValue.toUpperCase(); 
					currentField = $(this).parent().parent();
					currentField.find(".sqldatatype select").val(datatype).end()
						.find(".frontlist select").val(selectedValue).end()
						.find(".backlist select").val(selectedValue);	
					break;
				case "groupItemList":					
					break;
				case "linkedTableList":
					currentField = $(this).parent().parent();
					currentField.find(".sqldatatype select").val("NONE").end()
						.find(".frontlist select").val("relatedData")
						.find(".backlist select").val("none");	
					linkedTableHTML = $('#templates .linkedChildTable');
					$(this).parent().after(linkedTableHTML);
					$(".link_child_field").blur( function () {
						parent_field = currentField.parent();
						parent_fieldname = parent_field.find(".fieldNameInput").val();
						child_tablename = $(this).parent().find(".link_child_table").val();
						link_tablename = parent_fieldname + "_LINK_" + child_tablename;
						if (parent_fieldname == "") {
							alert("Remember to provide a parent_fieldname, dawg.");
							$(this).parents(".field").find(".fieldNameInput").focus();
						} else if (child_tablename == ""){
							alert("Remember to provide a child_tablename, dawg.");
							$(this).parents(".field").find(".link_child_table").focus();
						} else {
							$(this).parent().find(".link_tablename").val(link_tablename);
							log("Success: " + link_tablename);
						}
					} );
					break;
				default:
					break;
			} //end switch			
		}); //end dropDown select function
		
		$(".collapseAllFields").click(
			function () {
				var parentTable = $(this).closest('.table');
				if(parentTable.hasClass('collapsed')) {
					$(this).html("&mdash; Collapse All Fields");
					$(this).parent()
						.find(".fieldCollapse").html("&#151;").end()
						.find(".deleteField, .cloneField").show().end()
						.find(".fieldContents").slideDown("fast");
				} else {
					$(this).html("+ Expand All Fields");
					$(this).parent()
						.find(".fieldCollapse").html("&nbsp;+&nbsp;").end()
						.find(".deleteField, .cloneField").hide().end()
						.find(".fieldContents").slideUp("fast");
				}
				parentTable.toggleClass('collapsed');
				$.setFieldBehaviors();
			}	
		); //end .collapseAllFields function
		
	}; //end setFieldBehaviors()
	
	//#############################################################################
	//##################### 		END SET BEHAVIORS 		  #####################
	//#############################################################################

$(function() {
	var tableNum = 0;
	var fieldNum = 1;
	var globalNum = 1;
		
	var newField = $('#templates .field');

	var globalHTML = "<div class='globalVar'>Name : <input class='inputField' type='text' name='globalName'> Value : <input class='inputField' type='text' name='globalValue'><div class='deleteGlobalBtn deleteButton' id=''>Delete</div></div>";
	
	var newTable = $('#templates .table').clone().attr('id',++tableNum);
	
	$("#newTable").before(newTable);
	$(".newField").before(newField);
	$.setTableBehaviors();

	$("#newTable").click(function() {
		var newTable = $('#templates .table').clone().attr('id',++tableNum);
		$(this).before(newTable);
		//$(this).prev().find(".newField").before(newField);
		
		$.setTableBehaviors();
		
		// prevent the default click
		return false;
		
	}); //end function newTable.click()
	
	
	$("#addGlobal").click(function() {
		$(this).before(globalHTML);
		
		newDelGlobalBtn = $(this).prev().find('.deleteGlobalBtn'); 	//find the NEW DELETE GLOBALS BUTTON
		newDelGlobalBtnId = "delGlobalBtn" + globalNum;				//determine the NEW DELETE GLOBALS BUTTON id and assign to var
		newDelGlobalBtn.attr({id: newDelGlobalBtnId});				//set the NEW DELETE GLOBALS BUTTON id
		globalNum++;
		
		$("#" + newDelGlobalBtnId).click(function() {
			$(this).parent().remove();
		}); //end function delGlobal.click()
	}); //end function addGlobal.click()
	
	$("#submitBtn").click(function() {
		var xmlContent = "",
				optionString = "",
				thumbFieldXML = "",
				globalNameString, fieldNameString, fieldDisplayString, sqlDataTypeString, entryMethodStrHead, entryMethodStrEnd, frontlistString, backListString,
				optionsArray = [],
				defaultGlobals = {
					Images_Path	: 'assets/images/',
					Thumbs_Path	: 'assets/images/thumbs/',
					Audio_Path 	: 'assets/audio/',
					Movies_Path	: 'assets/video/',
					host				: 'localhost',
					database		: 'db_name',
					username		: 'user_name',
					password		: 'password',
					http_root		: 'http://localhost:8888/',
					server_root	: '/Applications/MAMP/htdocs/'
				}
		
		$("#specsWriteContainer .inputField").each(function () {
			var inputName = $(this).attr('name');
			var value = $(this).val();
			//log("inputName : " + inputName +"\nvalue : " + value + "\n" + xmlContent);	
			switch(inputName) {
				case "globalsStart":
					xmlContent += "\t<Globals>\n";
					break;
				case "globalName":
					globalNameString = value;
					break;
				case "globalValue":
					if (value.length === 0) {value = defaultGlobals[globalNameString];}
					xmlContent += "\t\t<"+globalNameString+">"+value+"</"+globalNameString+">\n";
					break;
				case "globalsEnd":
					xmlContent += "\t</Globals>\n"
					break;
				case "sitename":
					siteNameString = "\n<site name=\""+value+"\">\n";
					xmlContent += siteNameString;
					break;
				case "tablename":
					tableNameString = "\t<table name=\""+value+"\"";
					xmlContent += tableNameString;
					break;
				case "tabledisplayname":
					tableDisplayNameString = " displayname=\""+value+"\"";
					xmlContent += tableDisplayNameString;
					break;
				case "sortable":
					if ( $(this).attr('checked') ) {
						sortableString = " sortable=\"yes\"";
						xmlContent += sortableString;
					}
					break;
				case "static":
					if ( $(this).attr('checked') ) {
						staticString = " static=\"yes\"";
						xmlContent += staticString;
					}
					xmlContent += ">\n";
					break;
				case "field":
					fieldNameString = "\t\t<"+inputName+" name=\""+value+"\"";
					thumbParentName = value;
					break;
				case "fielddisplayname":
					fieldDisplayString = " displayname=\""+value+"\">\n";
					thumbParentDisplayName = value;
					break;
				case "sqldatatype":
					sqlDataTypeString = "\t\t\t<"+inputName+">"+value+"</"+inputName+">\n";
					break;		
				case "entrymethod":
					entryMethodStrHead = "\t\t\t<"+inputName;
					entryMethodStrBody = "";
					entryMethodStrEnd = ">"+value+"</"+inputName+">\n";
					break;
				case "width":
					entryMethodStrBody = " " + inputName+"=\""+value+"\" ";
					break;
				case "height":
					entryMethodStrBody += " " + inputName+"=\""+value+"\"";
					break;
				case "child_tablename":
					entryMethodStrBody = " " + inputName+"=\""+value+"\" ";
					break;
				case "child_fieldname":
					entryMethodStrBody += " " + inputName+"=\""+value+"\"";
					break;
				case "link_tablename":
					entryMethodStrBody += " " + inputName+"=\""+value+"\"";
					break;
				case "thumb_frontlist":
					thumbFrontList = value;
					break;
				case "thumb_backlist":
					thumbBackList = value;
					thumbFieldXML = "" + 
					"\t\t<field name=\"" + thumbParentName +"_thumb\" displayname=\"" + thumbParentDisplayName +" Thumbnail\">\n"+
						"\t\t\t<sqldatatype>TEXT</sqldatatype>\n" +
						"\t\t\t<entrymethod>fileUploadThumb</entrymethod>\n" +
/* 						"\t\t\t<frontlist>"+thumbFrontList+"</frontlist>\n"+ */
						"\t\t\t<backlist>"+thumbBackList+"</backlist>\n"+
					"\t\t</field>\n";
					break;
				case "frontlist":
					//frontlistString = "\t\t\t<"+inputName+">"+value+"</"+inputName+">\n";
					break;
				case "backlist":
					backListString = "\t\t\t<"+inputName+">"+value+"</"+inputName+">\n\t\t</field>\n";
					break;
				case "option":
					optionsArray.push(value);
					break;
				case "optionsEnd":
					break;
				case "globalsEnd":
					break; 
				case "fieldEnd":
					for ( var i in optionsArray ) {
						optionString += "\t\t\t<option>"+optionsArray[i]+"</option>\n";
						optionsArray[i] = null;
					}		
					xmlContent += fieldNameString + fieldDisplayString + optionString + sqlDataTypeString + entryMethodStrHead + entryMethodStrBody + entryMethodStrEnd  + backListString + thumbFieldXML;
					thumbFieldXML = " ";
					optionsArray = [];
					optionString = "";
					break; 
				case "tableEnd":
					xmlContent += "\t</table>\n";
					break;
				case "siteEnd":
					xmlContent += "</site>\n";
					break;		
				case "submitBtn":					
					break;
				default:
					xmlContent += "!Unrecognized Node!: "+inputName+" / " +value+"<br/>";
			} //end switch statement
		}); //end $("input").each()
		
		//$("#submitBtn").before("<input type='hidden' name='xmlContent' value='"+xmlContent+"'>");
		
		$.ajax({
		   type: "POST",
		   url: "write_xml.php",
		   data: "xmlContent="+xmlContent,
		   success: function(html){
				$("#linkToXML").html(html);
				$("#buildMetaBtn").click(function() {
						$.ajax({
				   type: "POST",
				   url: "meta.php",
				   data: "xmlFile=newSpecs.xml",
				   success: function(html){
						alert(html);
				   }
			   });
		
			});
		   }
		});
		
		return false;
	}); //end #submitButton function

});
